<script setup>
import Toast from '@vant/weapp/dist/toast/toast';

import newLoading from '@/components/newLoading/index.vue';
import bgInstruction from './child/bgInstruction.vue'
import { getCategoryDetail } from '@/api/home'
import { editImgUpload, imgToTxt, getImageByTaskId } from '@/api/painting'
import { ref } from 'vue'
import { onLoad, onReady, onUnload } from '@dcloudio/uni-app'

// 页面携带参数
const queryItem = ref({})
// 查询详情信息
const queryInfo = ref({})
// 查询参数
const queryParams = ref({})
// 提交数据
const queryData = ref({})
// tabs选中
const tabsCurrent = ref(0)
// 消耗算力
const expendNum = ref(0)
// 关键词数组
const keyWords = ref([])
// 背景指令ref
const bgInstructionRef = ref(null)
// 图片指令ref
const imgInstructionRef = ref(null)

const loading = ref(false);
const loadingRef = ref(null);

// 任务ID
const taskId = ref('')
let timer = null


// 上传图片
function uploadImg(e) {
    queryParams.value.baseImageUrl = e
}


// 校验方法
function verifyFn() {
    return new Promise((resolve, reject) => {
        if (!queryData.value.baseImageUrl) {
            Toast.fail('请上传图片')
            return reject()
        }
        resolve()
    })
}


// 开始生成
async function startFn() {
    if (tabsCurrent.value === 0) {
        queryData.value = bgInstructionRef.value.getQueryParams()
    } else {
        queryData.value = imgInstructionRef.value.getQueryParams()
    }
    await verifyFn()
    loading.value = true
    await editImgUploadFn()
    imgToTxtFn()
}

// 获取任务状态
async function getImageByTaskIdFn() {
    const res = await getImageByTaskId(taskId.value)
    if (res.data.state === 1) {
        clearInterval(timer);
        await loadingRef.value.completeLoading()
        res.data.tabType = tabsCurrent.value
        res.data.title = queryInfo.value.title
        uni.navigateTo({
            url: `/newEditionDraw/textContentProcessing/detail/index?data=${JSON.stringify(res.data)}`
        })
    } else if (![3, 4].includes(res.data.state)) {
        clearInterval(timer);
        const errorMessage = res.data?.remark.split('失败原因：')[1]
        Toast.fail(errorMessage);
        loading.value = false
    }
}



// 图生文任务提交
async function imgToTxtFn() {
    const res = await imgToTxt(queryData.value)
    taskId.value = res.data.taskId
    timer = setInterval(() => {
        getImageByTaskIdFn()
    }, 5000);
}

// 上传原图
async function editImgUploadFn() {
    return new Promise(async (resolve, reject) => {
        try {
            const res = await editImgUpload({
                type: 13,
                orgImg: queryParams.value.baseImageUrl
            })
            queryData.value.baseImageUrl = res.orgImgUrl
            resolve()
        } catch (error) {
            loading.value = false
            reject()
        }
    })
}



// 获取分类详情
async function getCategoryDetailFn() {
    const res = await getCategoryDetail(queryItem.value.id || 62)
    queryInfo.value = res.data
    res.data.categoryParam.forEach(item => {
        if (item.title === '背景关键词') {
            keyWords.value = item.data
        } else if (item.title === 'expendNum') {
            expendNum.value = item.data[0].title
        }
    })
}

// 加载关闭事件
function loadingClose() {
    clearInterval(timer);
}

onUnload(() => {
    clearInterval(timer);
    loading.value = false
})

onReady(() => {

})

onLoad((e) => {
    if (e.item) {
        queryItem.value = JSON.parse(e.item)
        if (queryItem.value.baseImageUrl) {
            queryParams.value.baseImageUrl = queryItem.value.baseImageUrl
        }

    }
    getCategoryDetailFn()
})
</script>

<template>
    <div class='textContentProcessing'>
        <NavBar>文案处理</NavBar>

        <div class="container">
            <bgInstruction ref="bgInstructionRef" :baseImageUrl="queryParams.baseImageUrl" :keyWords="keyWords"
                @uploadImg="uploadImg">
            </bgInstruction>

        </div>
        <div class="footer">
            <div class="footer_placeholder"></div>
            <div class="footer_content">
                <myDrawButton :expendNum="expendNum" @click="startFn"></myDrawButton>
            </div>
        </div>
    </div>
    <van-toast id="van-toast" />
    <newLoading ref="loadingRef" v-model="loading" :duration="10000" :label="['排队中，预计等待20秒']" @close="loadingClose">
    </newLoading>
</template>

<style lang='scss' scoped>
.textContentProcessing {

    .container {
        padding: 0 30rpx 30rpx;

        .tabs {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 40rpx;

            .tab {
                box-sizing: border-box;
                width: 335rpx;
                height: 64rpx;
                line-height: 64rpx;
                border-radius: 32rpx;
                text-align: center;
                font-size: 30rpx;
                color: #C2C2C2;
                border: 2rpx solid transparent;

                &.active {
                    color: #83CD88;
                    border: 2rpx solid #83CD88;
                }
            }
        }
    }

    .footer {
        .footer_placeholder {
            height: 176rpx;
        }

        .footer_content {
            box-sizing: border-box;
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 176rpx;
            background: #212142;
            padding: 28rpx 30rpx 0;
        }
    }
}
</style>